using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.ComponentModel.Design;
using Widgetsphere.Generator.Models;

namespace Widgetsphere.Generator.Design.Editors
{
	internal class ColumnSingleSelectEditor : System.Drawing.Design.UITypeEditor
	{
		public ColumnSingleSelectEditor()
		{
		}

		public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return System.Drawing.Design.UITypeEditorEditStyle.DropDown;
		}

		System.Windows.Forms.Design.IWindowsFormsEditorService edSvc = null;
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
      Reference retval = null;
      try
      {
        edSvc = (System.Windows.Forms.Design.IWindowsFormsEditorService)provider.GetService(typeof(System.Windows.Forms.Design.IWindowsFormsEditorService));

        Table table = (Table)context.Instance;
        ModelRoot root = (ModelRoot)table.Root;
        ReferenceCollection referenceCollection = table.Columns;

        //Create the list box 
        System.Windows.Forms.ListBox newBox = new System.Windows.Forms.ListBox();
        newBox.Click += new EventHandler(newBox_Click);
        newBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

        newBox.Items.Add("(Not Set)");
        foreach(Reference reference in referenceCollection)
        {
          Column column = ((ModelRoot)reference.Root).Database.Columns.GetById(reference.Ref)[0];
          newBox.Items.Add(column);
        }

        edSvc.DropDownControl(newBox);        
        if((newBox.SelectedIndex > 0) && (newBox.SelectedItem != null))
          retval = ((Column)newBox.SelectedItem).CreateRef();

      }
      catch(Exception ex) { }
      return retval;
    }

		private void newBox_Click(object sender, System.EventArgs e) 
		{ 
			if (edSvc != null)
				edSvc.CloseDropDown();
		}

	}
}
